import { ref, onMounted } from 'vue'
import { Modal } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import type { Menu } from '@/types/api/system/menu'
import { MenuType } from '@/types/api/system/menu'
import { useMenuStore } from '@/stores/system/menu'
import { storeToRefs } from 'pinia'
import { message } from 'ant-design-vue'

/**
 * 菜单管理页面逻辑钩子
 * @returns 菜单管理状态和方法
 */
export default function useMenuManagement() {
  // ------------ 国际化和工具引入 ------------
  const { t } = useI18n()
  
  // ------------ 使用状态管理 ------------
  const menuStore = useMenuStore()
  
  // 从store中提取响应式状态
  const { 
    loading, 
    submitLoading, 
    menuList,
    expandedKeys,
    isExpandAll,
    modalVisible,
    iconModalVisible,
    queryParams,
    form,
    formMode,
    formTitle,
    currentId,
    parentTreeData
  } = storeToRefs(menuStore)
  
  // ------------ 错误状态管理 ------------
  const loadError = ref(false)
  const errorMessage = ref('')
  
  // ------------ 组件引用 ------------
  const formRef = ref<FormInstance>()
  
  // 图标选择器状态
  const iconSelectorVisible = ref(false)
  
  /**
   * 获取所有可展开的节点ID
   */
  const getExpandKeys = (list: Menu[]): string[] => {
    const keys: string[] = []
    const traverse = (items: Menu[]) => {
      items.forEach(item => {
        if (item.children && item.children.length > 0) {
          keys.push(item.id)
          traverse(item.children)
        }
      })
    }
    traverse(list)
    return keys
  }
  
  // ------------ 表格交互方法 ------------
  /**
   * 处理表格展开行变化
   * @param keys 展开的行键
   */
  const onExpandedRowsChange = (keys: string[]) => {
    expandedKeys.value = keys
    isExpandAll.value = keys.length > 0 && menuList.value.length > 0 && 
      (keys.length === getExpandKeys(menuList.value).length)
  }
  
  // ------------ 搜索区域方法 ------------
  /**
   * 搜索处理
   */
  const handleSearch = () => {
    menuStore.fetchMenuList()
  }

  /**
   * 重置搜索
   */
  const handleReset = () => {
    queryParams.value.keyword = ''
    queryParams.value.status = undefined
    menuStore.fetchMenuList()
  }
  
  // ------------ 操作区域方法 ------------
  /**
   * 展开/折叠所有
   */
  const handleExpandAll = () => {
    if (isExpandAll.value) {
      expandedKeys.value = []
    } else {
      expandedKeys.value = getExpandKeys(menuList.value)
    }
    isExpandAll.value = !isExpandAll.value
  }

  /**
   * 刷新菜单列表
   */
  const handleRefresh = () => {
    menuStore.fetchMenuList()
  }
  
  // ------------ 表单操作方法 ------------
  /**
   * 添加菜单
   * @param record 父级菜单项（可选）
   */
  const handleAdd = (record?: Menu) => {
    formMode.value = 'add'
    menuStore.resetForm()
    
    // 如果传入了记录，表示添加子菜单
    if (record) {
      form.value.parentId = record.id
      
      // 如果父级是目录，则默认添加菜单，否则添加按钮
      if (record.type === MenuType.DIRECTORY) {
        form.value.type = MenuType.MENU
      } else if (record.type === MenuType.MENU) {
        form.value.type = MenuType.BUTTON
      }
    } else {
      form.value.parentId = '0'
      form.value.type = MenuType.DIRECTORY
    }
    
    menuStore.setFormModalVisible(true)
  }

  /**
   * 编辑菜单
   * @param record 菜单项
   */
  const handleEdit = async (record: Menu) => {
    if (!record || !record.id) {
      message.error(t('menu.invalidData'))
      return
    }

    try {
      // 设置编辑模式
      formMode.value = 'edit'
      
      // 保存当前ID
      const menuId = String(record.id).trim()
      currentId.value = menuId
      
      // 先重置表单，避免旧数据干扰
      menuStore.resetForm()
      
      // 直接使用传入的记录数据填充表单，无需请求接口
      Object.assign(form.value, {
        parentId: record.parentId ? String(record.parentId) : '0',
        type: record.type || MenuType.MENU,
        name: record.name || '',
        path: record.path || '',
        component: record.component || '',
        query: record.query || '',
        icon: record.icon || '',
        orderNum: Number(record.orderNum || 0),
        isVisible: Boolean(record.isVisible),
        status: Number(record.status ?? 1),
        permission: record.permission || '',
        isExternal: Boolean(record.isExternal),
        isCache: Boolean(record.isCache)
      })
      
      // 显示弹窗
      menuStore.setFormModalVisible(true)
    } catch (error) {
      message.error(error instanceof Error ? error.message : t('common.editFailed'))
    }
  }

  /**
   * 提交表单
   */
  const handleSubmit = async () => {
    try {
      await formRef.value?.validate()
      await menuStore.submitForm()
    } catch (error) {
      console.error('提交菜单表单失败:', error)
    }
  }
  
  // ------------ 删除操作方法 ------------
  /**
   * 删除菜单
   * @param record 菜单项
   */
  const handleDelete = (record: Menu) => {
    if (!record || !record.id) {
      message.error(t('menu.invalidData'))
      return
    }

    // 检查是否有子菜单
    if (record.children && record.children.length > 0) {
      Modal.confirm({
        title: t('menu.hasChildrenTitle'),
        content: t('menu.hasChildrenContent'),
        okText: t('common.confirm'),
        cancelText: t('common.cancel')
      })
      return
    }

    Modal.confirm({
      title: t('menu.confirmDelete'),
      content: t('menu.deleteConfirmContent', { name: record.name }),
      okText: t('common.confirm'),
      cancelText: t('common.cancel'),
      okType: 'danger',
      async onOk() {
        try {
          await menuStore.removeMenu(record.id)
        } catch (error) {
          message.error(t('common.deleteFailed'))
        }
      }
    })
  }
  
  // ------------ 状态管理方法 ------------
  /**
   * 修改菜单状态
   * @param checked 是否选中
   * @param record 菜单项
   */
  const handleStatusChange = async (checked: boolean, record: Menu) => {
    try {
      record.statusLoading = true
      const success = await menuStore.changeMenuStatusAction(record.id, checked ? 1 : 0)
      if (success) {
        record.status = checked ? 1 : 0
      }
    } catch (error) {
      record.status = checked ? 0 : 1
    } finally {
      record.statusLoading = false
    }
  }

  /**
   * 修改菜单可见性
   * @param record 菜单项
   * @param visible 是否可见
   */
  const handleVisibleChange = async (record: Menu, visible: boolean) => {
    const data = { ...record, isVisible: visible }
    await menuStore.changeMenuVisible(record.id, data)
  }
  
  // ------------ 数据获取方法 ------------
  /**
   * 获取菜单列表
   */
  const fetchMenuList = async () => {
    try {
      loadError.value = false
      errorMessage.value = ''
      await menuStore.fetchMenuList()
    } catch (error) {
      loadError.value = true
      errorMessage.value = error instanceof Error ? error.message : t('common.fetchError')
    }
  }
  
  // ------------ 初始化 ------------
  onMounted(() => {
    menuStore.fetchMenuList()
  })
  
  return {
    // 状态
    loading,
    submitLoading,
    modalVisible,
    iconModalVisible,
    menuList,
    expandedKeys,
    isExpandAll,
    queryParams,
    form,
    formMode,
    formTitle,
    currentId,
    parentTreeData,
    loadError,
    errorMessage,
    formRef,
    iconSelectorVisible,
    
    // 方法
    onExpandedRowsChange,
    handleSearch,
    handleReset,
    handleExpandAll,
    handleRefresh,
    handleAdd,
    handleEdit,
    handleSubmit,
    handleDelete,
    handleStatusChange,
    handleVisibleChange,
    fetchMenuList
  }
} 